package com.whosly.demo.jmh.util;

import java.math.BigDecimal;
import java.text.DecimalFormat;

/**
 * @author fengyang
 * @date 2023/6/29 下午4:28
 * @see <a href="fengyang@stoneatom.com">mailTo: fengyang@stoneatom.com</a>
 */
public class BytesUtil
{
    /**
     * 数值类型 转 KB,MB,GB...
     */
    public static String byteToM(Long size) {
        BigDecimal fileSize = new BigDecimal(size);
        BigDecimal param = new BigDecimal(1024);
        int dep = 0;
        while(fileSize.compareTo(param) > 0 && dep < 5)
        {
            fileSize = fileSize.divide(param);
            dep++;
        }

        DecimalFormat df = new DecimalFormat("#.##");
        String result = df.format(fileSize) + "";
        switch (dep) {
            case 0:
                result += "B";
                break;
            case 1:
                result += "KB";
                break;
            case 2:
                result += "MB";
                break;
            case 3:
                result += "GB";
                break;
            case 4:
                result += "TB";
                break;
            case 5:
                result += "PB";
                break;
        }
        return result;
    }

    /**
     * 数值类型 转 KB,MB,GB...
     */
    public static String byte2M(Long size) {
        long kb = 1024;
        long mb = kb * 1024;
        long gb = mb * 1024;
        if (size >= gb)
        {
            return String.format("%.1f GB", (float) size / gb);
        }
        else if (size >= mb)
        {
            float f = (float) size / mb;
            return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
        }
        else if (size >= kb)
        {
            float f = (float) size / kb;
            return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
        }
        else
        {
            return String.format("%d B", size);
        }
    }

}
